package cn.pku.eecs.ldn.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.util.Log;

public class StringUtil {
	private static final String TAG = "StringUtil";
	private static final boolean DEBUG = true;

	/**
	 * The returned value maybe null if an exception happened
	 * @param s
	 * @return
	 */
	public static String md5(String s) {
		if (s == null) {
			if (DEBUG)
				Log.e(TAG, "md5(): s is null, return null");
			return null;
		}
		String ret = null;
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(s.getBytes());
			byte[] hashValue = messageDigest.digest();
			StringBuffer hexStringBuffer = new StringBuffer();
			int length = hashValue.length;
			for (int i = 0; i < length; i++) {
				hexStringBuffer
						.append(Integer.toHexString(0xFF & hashValue[i]));
			}
			ret = hexStringBuffer.toString();
		} catch (NoSuchAlgorithmException e) {
			if (DEBUG)
				Log.e(TAG, e.getMessage(), e);
		} catch (Exception e) {
			if (DEBUG)
				Log.e(TAG, "md5(): encountered an unexpected exception: ");
			if (DEBUG)
				Log.e(TAG, e.getMessage(), e);
		}
		return ret;
	}
}
